package com.example.seey2023.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.seey2023.entity.ChinaTotal;
import com.example.seey2023.entity.LineTrend;
import com.example.seey2023.entity.NcovData;
import com.example.seey2023.entity.NcovNews;
import com.example.seey2023.service.ChinaTotalService;
import com.example.seey2023.service.IndexService;
import com.example.seey2023.service.NcovNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class IndexController {

    @Autowired
    private IndexService indexService;
    @Autowired
    private ChinaTotalService chinaTotalService;
    @Autowired
    private NcovNewsService ncovNewsService;

    /**
     * 修改为首页，内含ChinaMap查询chinatotal数据，一条最新数据
     *
     * @param model
     * @return
     */
    @RequestMapping("/")
    public String index(Model model) throws Exception {

        // 1.找到ID最大的那一条数据
        Integer id = chinaTotalService.maxID();
        // 2.根据ID进行数据查找
        ChinaTotal chinaTotal = chinaTotalService.getById(id);
        model.addAttribute("chinaTotal", chinaTotal);
        return "index";
    }

    @RequestMapping("/toChina")
    public String toChina(Model model) throws Exception {

        // 1.找到ID最大的那一条数据
        Integer id = chinaTotalService.maxID();
        // 2.根据ID进行数据查找
        /**
         * 2.1redis查询数据库的逻辑
         * 1.先查询Redis缓存，有数据则直接返回，没有数据则查询MySQL并更新Redis缓存，返回客户端
         */
        Jedis jedis = new Jedis("localhost");
//        Jedis jedis = new Jedis("114.116.105.96");

        // 2.2拿到客户端连接
        if (jedis != null) {
            String confirm = jedis.get("confirm");
            String input = jedis.get("input");
            String heal = jedis.get("heal");
            String dead = jedis.get("dead");
            String updateTime = jedis.get("updateTime");
            // 如果Redis缓存中有数据
            if (StringUtils.isNotBlank(confirm)
                    && StringUtils.isNotBlank(input)
                    && StringUtils.isNotBlank(heal)
                    && StringUtils.isNotBlank(dead)
                    && StringUtils.isNotBlank(updateTime)) {
                ChinaTotal chinaTotalRedis = new ChinaTotal();
                chinaTotalRedis.setConfirm(Integer.parseInt(confirm));
                chinaTotalRedis.setInput(Integer.parseInt(input));
                chinaTotalRedis.setHeal(Integer.parseInt(heal));
                chinaTotalRedis.setDead(Integer.parseInt(dead));

                chinaTotalRedis.setUpdateTime(new Date());
                System.out.println("Redis数据：" + chinaTotalRedis);
                // 将数据返回前台
                model.addAttribute("chinaTotal", chinaTotalRedis);
                // 3.疫情播报新闻
                List<NcovNews> newsList = ncovNewsService.listNewsLimit5();
                model.addAttribute("newsList", newsList);
                return "china";
            } else {
                // 2.3 缓存中没有数据，查询MySQL数据库
                ChinaTotal chinaTotal = chinaTotalService.getById(id);
                model.addAttribute("chinaTotal", chinaTotal);
                // 3.疫情播报新闻
                List<NcovNews> newsList = ncovNewsService.listNewsLimit5();
                model.addAttribute("newsList", newsList);
                // 2.4 更新缓存
                jedis.set("confirm", String.valueOf(chinaTotal.getConfirm()));
                jedis.set("input", String.valueOf(chinaTotal.getInput()));
                jedis.set("heal", String.valueOf(chinaTotal.getHeal()));
                jedis.set("dead", String.valueOf(chinaTotal.getDead()));
                jedis.set("updateTime", String.valueOf(chinaTotal.getUpdateTime()));
                return "china";
            }
        }

        ChinaTotal chinaTotal = chinaTotalService.getById(id);
        model.addAttribute("chinaTotal", chinaTotal);
        // 3.疫情播报新闻
        List<NcovNews> newsList = ncovNewsService.listNewsLimit5();
        model.addAttribute("newsList", newsList);
        return "china";
    }

    @RequestMapping("/query")
    @ResponseBody
    public List<NcovData> queryData() throws ParseException {
        // 每日更新的数据，使用场景
//        QueryWrapper<NcovData> queryWrapper = new QueryWrapper<>();
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        String format1 = format.format(new Date());
//        queryWrapper.ge("update_time",format.parse(format1));

        // 1. 先查redis缓存，有数据返回即可。
        Jedis jedis = new Jedis("localhost");
//        Jedis jedis = new Jedis("114.116.105.96");
        if (jedis != null) {
            // 1.1 有redis缓存数据，则返回数据
            List<String> listRedis = jedis.lrange("ncovdata", 0, 33);

            List<NcovData> dataList = new ArrayList<>();
            if (listRedis.size() > 0) {
                for (int i = 0; i < listRedis.size(); i++) {
                    System.out.println("列表项为：" + listRedis.get(i));
                    String s = listRedis.get(i);
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    Object name = jsonObject.get("name");
                    Object value = jsonObject.get("value");
                    NcovData ncovData = new NcovData();
                    ncovData.setName(String.valueOf(name));
                    ncovData.setValue(Integer.parseInt(value.toString()));
                    dataList.add(ncovData);
                }
                // 查询redis缓存，返回的数据
                return dataList;
            } else {

                // 1.2 没有redis缓存数据，查MySQL数据库，更新缓存
                List<NcovData> list = indexService.listOrderByIdLimit34();
                for (NcovData ncovData : list) {
                    jedis.lpush("ncovdata", JSONObject.toJSONString(ncovData));
                }
                return list;
            }
        }
        // 默认没有连接redis的返回数据库【兼容无redis服务情况】
        List<NcovData> list = indexService.listOrderByIdLimit34();
        return list;
    }

    // 跳转index页面
    @RequestMapping("/toIndex")
    public String toIndex() {
        return "index";//后缀会自动匹配
    }

    // 跳转pie页面
    @RequestMapping("/toPie")
    public String toPie() {
        return "pie";
    }

    /**
     * 分组聚合
     * SQL：select count(*) from goods group by type;
     */
    @RequestMapping("/queryPie")
    @ResponseBody
    public List<NcovData> queryPieData() {
        List<NcovData> list = indexService.listOrderByIdLimit34();
        return list;
    }

    // 跳转pie页面
    @RequestMapping("/toBar")
    public String toBar() {
        return "bar";
    }

    // 获取柱状图数据
    @RequestMapping("/queryBar")
    @ResponseBody
    public Map<String, List<Object>> queryBarData() {
        // 1.所有城市数据：数值
        List<NcovData> list = indexService.listOrderByIdLimit34();
        // 2.所有城市数据
        List<String> cityList = new ArrayList<>();
        for (NcovData data : list) {
            cityList.add(data.getName());
        }
        // 3.所有疫情数据
        List<Integer> dataList = new ArrayList<>();
        for (NcovData data : list) {
            dataList.add(data.getValue());
        }

        // 4.创建Map
        Map map = new HashMap();
        map.put("cityList", cityList);
        map.put("dataList", dataList);
        return map;
    }

    // 跳转line页面
    @RequestMapping("/toLine")
    public String toLine() {
        return "line";
    }

    // 获取line数据

    /**
     * select * from qvshishuju order by create_time limit 7;
     *
     * @return
     */
    @RequestMapping("/queryLine")
    @ResponseBody
    public Map<String, List<Object>> queryLineData() {
        // 1.查询近七天所有的数据
        List<LineTrend> list7Day = indexService.findSevenData();
        // 2.封装所有的确诊人数
        List<Integer> confirmList = new ArrayList<>();
        // 3.封装所有的隔离人数
        List<Integer> isolationList = new ArrayList<>();
        // 4.封装所有的治愈人数
        List<Integer> cureList = new ArrayList<>();
        // 5.封装所有的死亡人数
        List<Integer> deadList = new ArrayList<>();
        // 6.封装所有的疑似人数
        List<Integer> similarList = new ArrayList<>();
        for (LineTrend data : list7Day) {
            confirmList.add(data.getConfirm());
            isolationList.add(data.getIsolation());
            cureList.add(data.getCure());
            deadList.add(data.getDead());
            similarList.add(data.getSimilar());
        }
        // 7.返回时间的格式容器Map
        Map map = new HashMap();
        map.put("confirmList", confirmList);
        map.put("isolationList", isolationList);
        map.put("cureList", cureList);
        map.put("deadList", deadList);
        map.put("similarList", similarList);
        return map;
    }

    /**
     * 国内实时疫情趋势图
     */
    @RequestMapping("/toTrendTime")
    public String toTrendIncrease() {
        return "trend2";
    }


}
